<template>
  <div class="app-container">
    <el-page-header @back="handleBack" content="商品SKU详情" />
    <el-card shadow="hover" class="mt-4">
      <!-- 基础信息区域 -->
      <el-descriptions
        title="基础信息"
        :column="1"
        border
        class="mb-6 basic-info-descriptions"
        label-width="120px">
        <!-- SPU信息 -->
        <el-descriptions-item label="所属SPU">
          {{ form.spuName || "-" }}
        </el-descriptions-item>

        <!-- SKU编码 -->
        <el-descriptions-item label="SKU编码">
          {{ form.code || "-" }}
        </el-descriptions-item>

        <!-- 商品分类 -->
        <!-- <el-descriptions-item label="商品分类">
          {{ form.categoryName || "-" }}
        </el-descriptions-item> -->

        <!-- 销售价 -->
        <el-descriptions-item label="销售价">
          {{ form.price || "-" }}
        </el-descriptions-item>

        <!-- 原价 -->
        <el-descriptions-item label="原价">
          {{ form.originalPrice || "-" }}
        </el-descriptions-item>

        <!-- 成本价 -->
        <el-descriptions-item label="成本价">
          {{ form.costPrice || "-" }}
        </el-descriptions-item>

        <!-- 库存数量 -->
        <el-descriptions-item label="库存数量">
          {{ form.stock || "-" }}
        </el-descriptions-item>

        <!-- 库存预警值 -->
        <el-descriptions-item label="库存预警值">
          {{ form.lowStock || "-" }}
        </el-descriptions-item>

        <!-- 重量 -->
        <el-descriptions-item label="重量(g) 用于物流">
          {{ form.weight || "-" }}
        </el-descriptions-item>

        <!-- 体积 -->
        <el-descriptions-item label="体积(cm³) 用于物流">
          {{ form.volume || "-" }}
        </el-descriptions-item>

        <!-- 商品状态 -->
        <el-descriptions-item label="商品状态">
          <el-tag :type="form.status === 1 ? 'success' : 'danger'">
            {{ form.status === 1 ? "启用" : "禁用" }}
          </el-tag>
        </el-descriptions-item>

        <!-- 新增字段开始 -->
        <el-descriptions-item label="SKU名称">
          {{ form.skuName || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="创建人">
          {{ form.createBy || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="更新人">
          {{ form.updateBy || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ form.createdAt || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ form.updatedAt || "-" }}
        </el-descriptions-item>
        <!-- 新增字段结束 -->
      </el-descriptions>

      <!-- 商品图片区域 -->
      <el-descriptions title="商品图片" :column="1" border class="mb-6">
        <el-descriptions-item label="图片展示">
          <div class="image-group">
            <el-image
              v-for="(img, idx) in form.productImages"
              :key="idx"
              :src="`${proxy.$baseUrl || ''}${img.url}`"
              :preview-src-list="
                form.productImages.map(
                  (item) => `${proxy.$baseUrl || ''}${item.url}`
                )
              "
              class="image-item"
              fit="cover" />
            <div v-if="form.productImages.length === 0" class="empty-image">
              暂无图片
            </div>
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 规格值区域：修复未定义index问题 -->
      <el-descriptions
        v-for="(group, groupIdx) in data.specGroups"
        :key="groupIdx"
        :title="group.label"
        :column="1"
        border
        class="mb-6 basic-info-descriptions"
        label-width="120px">
        <!-- 修复：添加key+处理空数组+用itemIdx匹配值 -->
        <el-descriptions-item
          v-for="(item, itemIdx) in getSpecTypeData(group.type)
            ?.specItemGroup || []"
          :key="`spec-${group.type}-${itemIdx}`"
          :label="item.specName">
          <!-- 修复：通过规格名匹配值，而非未定义的index -->
          {{ getSpecValueByKey(item.specName) || "-" }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 返回按钮 -->
      <div class="mt-8 text-center">
        <el-button @click="handleBack">返回列表</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup name="SkuDetail">
// 接口引入
import { getSku } from "@/api/product/sku";
import { listProductCategory } from "@/api/product/productCategory";
import { listProductSpu } from "@/api/product/productSpu";
import {
  getProductSpecTemplate,
  listProductSpecTemplate,
  getProductSpecTemplateGrouped,
} from "@/api/product/productSpecTemplate";

// 依赖引入
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from "vue";
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

// 数据源
const productCategoryOptions = ref([]); // 分类列表（匹配名称用）
const productSpuList = ref([]); // SPU列表（匹配名称用）
const productSpecTemplateList = ref([]); // 模板列表（匹配名称用）

// 查询参数
const queryAllParams = ref({ pageSize: 9999 });

// 详情数据：修复form缺少specSelections+规格组字段类型
const data = reactive({
  form: {
    id: null, // SKU主键ID
    spuId: null,
    spuName: "-", // SPU名称（回显用）
    code: "-",
    categoryId: null,
    categoryName: "-", // 分类名称（回显用）
    templateId: null,
    templateName: "-", // 模板名称（回显用）
    specValues: [], // 动态属性值
    price: "-",
    originalPrice: "-",
    costPrice: "-",
    stock: "-",
    lowStock: "-",
    weight: "-",
    volume: "-",
    productImages: [], // 商品图片
    status: 1, // 状态：1-启用，0-禁用
    // 新增字段：修复初始类型（specNameGroup/specValueGroup应为数组）
    skuName: "-",
    specNameGroup: [], // 后端返回数组，避免字符串处理问题
    specValueGroup: [], // 后端返回数组，避免字符串处理问题
    createBy: "-",
    updateBy: "-",
    createdAt: "-",
    updatedAt: "-",
    // 修复：添加规格选中值载体（回显时需要）
    specSelections: {
      0: [], // specType=0（售卖属性）
      1: [], // specType=1（基础属性）
      3: [], // specType=3（overview属性）
      4: [], // specType=4（其它属性）
    },
  },
  // 规格分组配置
  specGroups: [
    { type: 0, label: "售卖属性" },
    { type: 1, label: "基础属性" },
    { type: 3, label: "overview属性" },
    { type: 4, label: "其它属性" },
  ],
  // 规格数据源
  specData: {
    specTypes: [
      {
        specType: 0,
        specItemGroup: [
          {
            specName: "Color",
            specValueGroup: [
              "Black",
              "Walnut",
              "White",
              "Beige",
              "Light Gray",
              "Blush Pink",
              "Navy Blue",
              "Olive Green",
              "Charcoal",
              "Emerald Green",
              "Oak",
              "Maple",
              "Cherry",
              "Pine",
              "White & Gold",
              "Gray & Chrome",
              "Brown & Brass",
            ],
          },
          { specName: "Lighted", specValueGroup: ["Yes", "No"] },
          {
            specName: "Material",
            specValueGroup: [
              "MDF",
              "Solid Oak",
              "Solid Walnut",
              "Solid Pine",
              "Solid Teak",
              "Particle Board",
              "Plywood",
              "HDF",
              "Melamine-Faced MDF",
              "Linen",
              "Polyester",
              "Velvet",
              "Leatherette",
              "PE Rattan",
              "Aluminum",
              "Chrome",
              "Iron",
              "Stainless Steel",
            ],
          },
          {
            specName: "Size",
            specValueGroup: [
              "1790mmW × 375mmD × 360mmH",
              "1200mmW×400mmD×450mmH",
              "1500mmW×380mmD×420mmH",
              "1800mmW×420mmD×480mmH",
              "2200mmW×450mmD×500mmH",
              "2200mmW×900mmD×850mmH",
            ],
          },
        ],
      },
      {
        specType: 1,
        specItemGroup: [
          {
            specName: "Adjustable Shelves",
            specValueGroup: [
              "No",
              "Yes (3-Speed Adjustment)",
              "Yes (5-Speed Adjustment)",
              "Yes (Removable Shelves)",
            ],
          },
          {
            specName: "Assembly",
            specValueGroup: ["Fully", "Required", "Partial", "Professional"],
          },
          {
            specName: "Cabinet Feature",
            specValueGroup: [
              "Extendable",
              "With Drawers",
              "LED",
              "With Cabinets",
              "With Open Shelves",
              "With Hidden Storage",
              "Lockable",
              "Waterproof",
              "Heat-Resistant",
            ],
          },
          {
            specName: "Cable Management",
            specValueGroup: [
              "No",
              "Yes (Hidden Cable Hole)",
              "Yes (Detachable Cable Organizer)",
              "Yes (Magnetic Cable Clips)",
            ],
          },
          {
            specName: "Number Of Drawers",
            specValueGroup: ["3", "0", "1", "2", "4", "5"],
          },
          {
            specName: "Product Care",
            specValueGroup: [
              "Wipe Clean With Damp Cloth, Wipe Dry With Clean Cloth",
              "Avoid Direct Sunlight, Wipe With Mild Soap Solution, Dry Immediately",
              "Do Not Use Abrasive Cleaners, Wipe With Leather Conditioner Every 3 Months",
            ],
          },
          {
            specName: "Style",
            specValueGroup: [
              "Modern",
              "Mid-Century Modern",
              "Industrial",
              "Bohemian",
              "Rustic",
              "Minimalist",
              "Luxury",
              "Coastal",
            ],
          },
          {
            specName: "Suggested Number Of People For Installation",
            specValueGroup: [
              "1 Person",
              "2 People",
              "3 People",
              "Professional Team",
            ],
          },
          {
            specName: "TV Size Ranges",
            specValueGroup: [
              "80 Inch TVs And Larger",
              "32-40 Inch TVs",
              "42-55 Inch TVs",
              "56-65 Inch TVs",
              "66-79 Inch TVs",
              "Universal (32-85 Inch TVs)",
            ],
          },
          {
            specName: "Tv Stand Type",
            specValueGroup: [
              "Freestanding TV Stand",
              "Wall-Mounted TV Stand",
              "Corner TV Stand",
              "Floating TV Stand",
              "Modular TV Stand",
            ],
          },
          {
            specName: "Voltage",
            specValueGroup: [
              "220-240V",
              "110-120V",
              "Dual Voltage (110-240V)",
              "12V (Low-Voltage for LED)",
            ],
          },
          {
            specName: "Warranty",
            specValueGroup: [
              "1 Year Limited",
              "2 Years Limited",
              "3 Years Limited",
              "5 Years Limited",
              "Lifetime Limited",
            ],
          },
        ],
      },
      {
        specType: 2,
        specItemGroup: [
          {
            specName: "Adjustable Shelves",
            specValueGroup: [
              "No",
              "Yes (3-Speed Adjustment)",
              "Yes (5-Speed Adjustment)",
              "Yes (Removable Shelves)",
            ],
          },
          {
            specName: "Assembly",
            specValueGroup: ["Fully", "Required", "Partial", "Professional"],
          },
          {
            specName: "Cable Management",
            specValueGroup: [
              "No",
              "Yes (Hidden Cable Hole)",
              "Yes (Detachable Cable Organizer)",
              "Yes (Magnetic Cable Clips)",
            ],
          },
          {
            specName: "Number Of Drawers",
            specValueGroup: ["3", "0", "1", "2", "4", "5"],
          },
          {
            specName: "Warranty",
            specValueGroup: [
              "1 Year Limited",
              "2 Years Limited",
              "3 Years Limited",
              "5 Years Limited",
              "Lifetime Limited",
            ],
          },
        ],
      },
      {
        specType: 3,
        specItemGroup: [
          {
            specName: "Overall Depth",
            specValueGroup: [
              "375mm",
              "320mm",
              "350mm",
              "380mm",
              "400mm",
              "420mm",
              "450mm",
            ],
          },
          {
            specName: "Overall Height",
            specValueGroup: [
              "360mm",
              "320mm",
              "400mm",
              "450mm",
              "500mm",
              "550mm",
              "600mm",
            ],
          },
          {
            specName: "Overall Width",
            specValueGroup: [
              "2550mm",
              "900mm",
              "1200mm",
              "1500mm",
              "1800mm",
              "2000mm",
              "2200mm",
            ],
          },
        ],
      },
    ],
  },
});

const { form } = toRefs(data);

/**
 * 1. 修复：根据specType获取规格数据
 */
const getSpecTypeData = (type) => {
  return data.specData.specTypes.find((item) => item.specType === type) || null;
};

/**
 * 2. 修复：根据规格名匹配对应值（解决未定义index问题）
 */
const getSpecValueByKey = (specName) => {
  // 处理specNameGroup/specValueGroup为空的情况
  if (
    !Array.isArray(form.value.specNameGroup) ||
    !Array.isArray(form.value.specValueGroup)
  ) {
    return null;
  }
  // 找到规格名对应的索引，再取对应值
  const nameIndex = form.value.specNameGroup.findIndex(
    (name) => name?.trim() === specName?.trim()
  );
  return nameIndex > -1 ? form.value.specValueGroup[nameIndex] : null;
};

/**
 * 3. 修复：返回列表页面（无错误）
 */
function handleBack() {
  const obj = { path: "/product/sku" };
  proxy.$tab.closeOpenPage(obj);
}

/**
 * 4. 修复：获取商品分类（添加错误处理）
 */
function getCategoryList() {
  return new Promise((resolve, reject) => {
    listProductCategory(queryAllParams.value)
      .then((response) => {
        productCategoryOptions.value = proxy.handleTree(
          response.data,
          "id",
          "parentId"
        );
        resolve();
      })
      .catch((err) => {
        proxy.$modal.msgError(err.msg || "获取分类列表失败");
        reject(err);
      });
  });
}

/**
 * 5. 修复：获取SPU列表（添加错误处理）
 */
function getSpuList() {
  return new Promise((resolve, reject) => {
    listProductSpu(queryAllParams.value)
      .then((response) => {
        productSpuList.value = response.rows;
        resolve();
      })
      .catch((err) => {
        proxy.$modal.msgError(err.msg || "获取SPU列表失败");
        reject(err);
      });
  });
}

/**
 * 6. 修复：获取属性模板列表（添加错误处理）
 */
function getTemplateList() {
  return new Promise((resolve, reject) => {
    listProductSpecTemplate(queryAllParams.value)
      .then((response) => {
        productSpecTemplateList.value = response.rows;
        resolve();
      })
      .catch((err) => {
        proxy.$modal.msgError(err.msg || "获取模板列表失败");
        reject(err);
      });
  });
}

/**
 * 7. 修复：加载模板属性（统一ID类型+错误处理）
 */
function loadTemplateSpecs(templateId) {
  if (!templateId) return;
  // 统一转为数字类型，避免字符串匹配失败
  const templateIdNum = Number(templateId);
  getProductSpecTemplate(templateIdNum)
    .then((response) => {
      const template = response.data;
      const validSpecs = (template.relationList || [])
        .filter((relation) => relation.productSpec && relation.productSpec.id)
        .map((relation) => ({
          ...relation.productSpec,
          relation: relation,
        }))
        .sort((a, b) => (a.relation.sort || 0) - (b.relation.sort || 0));
      // 若需要模板属性表格，可在此处处理（原代码注释未启用，暂保留逻辑）
    })
    .catch((err) => {
      proxy.$modal.msgError(err.msg || "获取模板属性失败");
    });
}

/**
 * 8. 修复：获取规格可选值（统一ID类型+错误处理）
 */
function getProductSpecTemplateGroupedApi(templateId) {
  if (!templateId) return;
  const templateIdNum = Number(templateId);
  getProductSpecTemplateGrouped(templateIdNum)
    .then((res) => {
      console.log("规格可选值：", res.data);
    })
    .catch((err) => {
      proxy.$modal.msgError(err.msg || "获取规格可选值失败");
    });
}

/**
 * 9. 修复：规格值回显（处理数组类型+统一匹配逻辑）
 */
function handleSpecSelectionsEcho() {
  // 构建规格名-值映射表
  const specMap = {};
  if (
    Array.isArray(form.value.specNameGroup) &&
    Array.isArray(form.value.specValueGroup)
  ) {
    form.value.specNameGroup.forEach((name, idx) => {
      if (name && form.value.specValueGroup[idx]) {
        specMap[name.trim()] = form.value.specValueGroup[idx].trim();
      }
    });
  }

  // 遍历规格组赋值
  data.specGroups.forEach((group) => {
    const specType = group.type;
    const specTypeData = getSpecTypeData(specType);
    if (specTypeData?.specItemGroup) {
      form.value.specSelections[specType] = specTypeData.specItemGroup.map(
        (item) => {
          return specMap[item.specName.trim()] || item.specValueGroup[0] || "-";
        }
      );
    }
  });
}

/**
 * 10. 核心修复：获取SKU详情（函数移出嵌套+类型统一+错误处理）
 */
function getSkuDetail(id) {
  if (!id) return;
  const idNum = Number(id); // 统一ID为数字类型
  getSku(idNum)
    .then((response) => {
      const skuData = response.data;
      console.log("商品SKU详情：", skuData);

      // 基础数据赋值：保留form原有结构（避免specSelections丢失）
      form.value = {
        ...form.value,
        ...skuData,
        // 统一数字类型，避免下拉框/匹配失败
        id: Number(skuData.id) || null,
        spuId: skuData.spuId ? Number(skuData.spuId) : null,
        categoryId: skuData.categoryId ? Number(skuData.categoryId) : null,
        templateId: skuData.templateId ? Number(skuData.templateId) : null,
        status: skuData.status ? Number(skuData.status) : 1,
        stock: skuData.stock ? Number(skuData.stock) : "-",
        lowStock: skuData.lowStock ? Number(skuData.lowStock) : "-",
        weight: skuData.weight ? Number(skuData.weight) : "-",
        volume: skuData.volume ? Number(skuData.volume) : "-",
        // 处理图片格式（补充基础路径）
        productImages: (skuData.productImages || []).map((img) => ({
          id: img.id ? Number(img.id) : null,
          url: img.url || "",
          sort: img.sort ? Number(img.sort) : 0,
        })),
        // 处理规格组字段（确保为数组）
        specNameGroup: Array.isArray(skuData.specNameGroup)
          ? skuData.specNameGroup
          : [],
        specValueGroup: Array.isArray(skuData.specValueGroup)
          ? skuData.specValueGroup
          : [],
        // 兜底默认值
        skuName: skuData.skuName || "-",
        createBy: skuData.createBy || "-",
        updateBy: skuData.updateBy || "-",
        createdAt: skuData.createdAt || "-",
        updatedAt: skuData.updatedAt || "-",
      };

      // 匹配SPU名称（统一数字类型匹配）
      const matchSpu = productSpuList.value.find(
        (spu) => Number(spu.id) === Number(form.value.spuId)
      );
      if (matchSpu) form.value.spuName = matchSpu.name;

      // 匹配分类名称（递归查找+统一数字类型）
      const findCategoryName = (id, list) => {
        for (const item of list) {
          if (Number(item.id) === Number(id)) return item.name;
          if (item.children && item.children.length > 0) {
            const name = findCategoryName(id, item.children);
            if (name) return name;
          }
        }
        return "-";
      };
      form.value.categoryName = findCategoryName(
        form.value.categoryId,
        productCategoryOptions.value
      );

      // 匹配模板名称+加载模板属性
      const matchTemplate = productSpecTemplateList.value.find(
        (tpl) => Number(tpl.id) === Number(form.value.templateId)
      );
      if (matchTemplate) form.value.templateName = matchTemplate.name;
      loadTemplateSpecs(form.value.templateId);

      // 规格值回显
      handleSpecSelectionsEcho();

      // 加载规格可选值
      getProductSpecTemplateGroupedApi(form.value.templateId);
    })
    .catch((err) => {
      proxy.$modal.msgError(err.msg || "获取SKU详情失败");
    });
}

/**
 * 11. 修复：页面初始化（并行加载+移除未定义函数调用）
 */
onMounted(() => {
  const id = route.params.id;
  if (!id) {
    proxy.$modal.msgError("缺少SKU ID参数");
    handleBack();
    return;
  }

  // 并行加载基础列表，确保详情加载时数据已就绪（比setTimeout更可靠）
  Promise.all([getCategoryList(), getSpuList(), getTemplateList()])
    .then(() => {
      getSkuDetail(id);
    })
    .catch(() => {
      // 基础列表加载失败仍尝试获取详情（降级处理）
      getSkuDetail(id);
    });
});
</script>

<style scoped>
/* 图片展示样式 */
.image-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}
.image-item {
  width: 100px;
  height: 100px;
  border: 1px solid #eee;
  cursor: pointer;
}
.empty-image {
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
}

/* 基础信息样式优化 */
.basic-info-descriptions :deep(.el-descriptions-item) {
  display: block !important;
  margin-bottom: 8px !important;
}
.basic-info-descriptions :deep(.el-descriptions-item__label) {
  display: inline-block !important;
  width: 120px !important;
  min-width: 120px !important;
  text-align: right !important;
  white-space: nowrap !important;
  vertical-align: top !important;
  margin-right: 8px !important;
}
.basic-info-descriptions :deep(.el-descriptions-item__content) {
  display: inline-block !important;
  width: calc(100% - 136px) !important;
  padding: 0 !important;
  vertical-align: top !important;
}
</style>
